/**
 * Created by ospip on 2017/9/25.
 * Copyright (c) 2017 LLAP. All rights reserved.
 */
public class BinaryNode<T extends Comparable<? super T>> implements Comparable<BinaryNode<T>> {

    public T data;
    public BinaryNode<T> leftChild;
    public BinaryNode<T> rightChild;

    public BinaryNode(T data, BinaryNode<T> lChild, BinaryNode<T> rChild) {
        this.data = data;
        this.leftChild = lChild;
        this.rightChild = rChild;
    }

    @Override
    public int compareTo(BinaryNode<T> o) {
        if (o == null || o.data == null || this.data == null) return 0;
        return this.data.compareTo(o.data);
    }

    public BinaryNode(T data) {
        this(data, null, null);
    }

    public BinaryNode() {
        this(null, null, null);
    }

    public BinaryNode<T> copy() {
        return new BinaryNode<>(this.data);
    }

    /* 打印广义表*/
    public void printGenList() {
        System.out.print(data.toString());
        if (leftChild == null && rightChild == null) return;    // 最底层叶节点
        System.out.print("(");
        if (leftChild != null) leftChild.printGenList();
        System.out.print(",");
        if (rightChild != null) rightChild.printGenList();
        System.out.print(")");
    }

    @Override
    public String toString() {
        String ret = data.toString();
        if (leftChild == null && rightChild == null) return ret;
        ret += "(";
        if (leftChild != null) ret += leftChild.toString();
        ret += ",";
        if (rightChild != null) ret += rightChild.toString();
        ret += ")";
        return ret;
    }

    public static void main(String[] args) {
        BinaryNode<String> tree = new BinaryNode<>("A");
        tree.leftChild = new BinaryNode<>("B");
        tree.leftChild.rightChild = new BinaryNode<>("C");
        tree.rightChild = new BinaryNode<>("D");
        System.out.println(tree);
    }
}
